
<%@ page pageEncoding="UTF-8"%>
<%@page import="itsm.isperp.framework.core.context.ContextHolder"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="isperp" uri="/WEB-INF/tlds/isperp.tld"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<script type="text/javascript" src="js/libs/util/map.js"></script>
<script type="text/javascript"
	src="http://api.map.baidu.com/api?v=2.0&ak=<%=ContextHolder.getConfigByKey("baiduApk")%>"></script>
<script type="text/javascript">
function formatterCi(cellvalue, rowObject, id,manageCode) {
		var mId = "${model.id}";
		if (id == mId) {
			return cellvalue+ '（'+manageCode+'）';
		} else {
			return '<a class="nui-txt-link" href="javascript:void(0)" onclick="isperp.openDialog({contentUrl:\'configuration/ci/edit?id=' + id + '\'})">' + cellvalue + '（'+manageCode+'）</a>';
		}
	}
function gridActions(rowObject) {
        var url="";
        if(rowObject.type_key=="sparepartIn")
        {
            url="sparepart/sparepartIn/view?id="+rowObject.id;
        }else if(rowObject.type_key=="sparepartOut")
        {
           url="sparepart/sparepartOut/view?id="+rowObject.id;
        }else if(rowObject.type_key=="sparepartDiscard")
        {
           url="sparepart/sparepartDiscard/view?id="+rowObject.id;
        }else if(rowObject.type_key=="sparepartBack")
        {
           url="sparepart/sparepartBack/view?id="+rowObject.id;
        }
       
		return isperp.createGridAction({
			title : '查看',
			iconCls : 'icon-view',
			onclick : "isperp.openDialog({title:'查看',contentUrl:'"+url+"'})"
		});
	}
	
	function searchByStationName() {
		var myGeo = new BMap.Geocoder();
		var address=$("#address").val();
		// 将地址解析结果显示在地图上,并调整地图视野
		myGeo.getPoint(address, function(point) {
			if (point) {
			   //alert(point.lat);
			   //alert(point.lng);
			   var lngId=$("#tmp_lng").val();
			   var latId=$("#tmp_lat").val();
			   $("#"+lngId).val(point.lng);
			   $("#"+latId).val(point.lat);
			} else {
				//alert("您选择地址没有解析到结果!");
			}
		}, "山东省");
	}
</script>
<form:form commandName="model" cssClass="validate" id="ciForm"
	action="configuration/ci/save">
	<form:hidden path="id" />
	<input type="text" id="tmp_lng" title="经度ID" style="display:none">
	<input type="text" id="tmp_lat" title="纬度ID" style="display:none">

	<input type="hidden" name="changeId" value="${changeId }" />
	<input type="hidden" value="${editStatus }" />
	<c:if test="${ty eq 'companyCi' }">
		<form:hidden path="areCompany" value="1" />
	</c:if>


	<div id="confCiTab" class="box tabbedBox">
		<div class="header">
			<ul>
				<li class="current"><a href="#basicInfo">资产信息</a>
				</li>
				<li><a href="#relatedCi"
					data-beforeclick="relatedCi_beforeClick();">关联资产(<label
						id="ciRelatedCiCount" style="color:red"></label>)</a></li>
				<li><a href="#relatedDataLog">数据修改日志(<label
						id="ciDataLogCount" style="color:red"></label>)</a></li>
				<li><a href="#relatedIncident">事件履历(<label
						id="ciIncidentCount" style="color:red"></label>)</a>
				</li>
				<li><a href="#relatedChange">变更履历(<label id="ciChangeCount"
						style="color:red"></label>)</a>
				</li>
				<li><a href="#relatedTaskCiInspect">巡检履历(<label
						id="ciInspectCount" style="color:red"></label>)</a>
				</li>

				<c:if test="${(ty ne 'sparepartIn') or (empty ty)}">
					<li><a href="#relatedSparepart">出入库履历(<label
							id="ciRelatedCiSparepartCount" style="color:red">0</label>)</a></li>
				</c:if>

			</ul>
			<h2>&nbsp;</h2>
		</div>
		<div style="padding:0" class="content tabbed">
			<div id="basicInfo">
				<div class="box  no-border">
					<div class="header">
						<h3>&nbsp;&nbsp;基本信息</h3>
					</div>
					<div style="float:left;width:100%;">
						<table class=" form-table" style="table-layout: fixed;width:100%;"
							id="basicInfoTable1">
							<tbody>
								<tr>

									<td class="td1">编号：</td>
									<td class="td2"><c:choose>

											<c:when test="${editStatus eq 1 }">
												<form:input path="code" cssClass="required" />
											</c:when>
											<c:otherwise>
												<form:hidden path="code" />
												<label style="color:#222;font-weight: 700;font-size: 14px">
													${model.code } </label>

											</c:otherwise>

										</c:choose>
									</td>
									<td class="td1">名称：</td>
									<td class="td2"><form:input path="name"
											cssClass="required" /></td>

								</tr>

								<tr>
									<td class="td1">类别：</td>
									<td class="td2"><form:hidden path="confCategoryId" /> <isperp:treeSelector
											id="confCategoryName" name="confCategoryName"
											displayValueCssClass="required"
											afterSelected="setCategoryProperty(ids,names,treeNode);"
											url="configuration/category/getTree?ty=${ty }"
											valueControlId="confCategoryId"
											displayValue="${model.confCategoryName}"></isperp:treeSelector>
									</td>

									<td class="td1">序列号：</td>
									<td class="td2"><form:input path="assetCode"
											cssClass="required" />
									</td>


								</tr>
								<tr>
									<td class="td1">规格：</td>
									<td class="td2"><form:input path="specification"
											cssClass="required" />
									</td>
									<td class="td1">型号：</td>
									<td class="td2"><form:input path="model" cssClass="" />
									</td>
								</tr>
								<tr>
									<td class="td1">所属客户：</td>
									<td class="td2"><form:hidden path="cusCustomerId" /> <isperp:listSelector
											id="customerSelector" url="customer/customer/list"
											afterSelected="cusCustomerId_afterSelected(rows);"
											name="cusCustomerName" displayValueCssClass="required"
											displayValue="${model.cusCustomerName }"
											valueControlId="cusCustomerId">
											<isperp:column name="id" title="id" hidden="true" width="10"></isperp:column>
											<isperp:column name="name" title="名称" width="150">
											</isperp:column>
											<isperp:column name="type" title="类型" width="80">
											</isperp:column>
											<isperp:column name="linkman" title="联系人" width="80">
											</isperp:column>
											<isperp:column name="linktel" title="联系电话" width="80">
											</isperp:column>
										</isperp:listSelector></td>

									<td class="td1">位置：</td>
									<td class="td2"><form:hidden path="locationId" /> <isperp:treeSelector
											id="locationName" name="locationName" displayValueCssStyle=""
											asyncLoad="false" displayValueCssClass=""
											url="configuration/location/getTree"
											valueControlId="locationId"
											displayValue="${model.locationName}"></isperp:treeSelector>
									</td>

								</tr>
								<tr>
									<td class="td1">购入价格：</td>
									<td class="td2" colspan="3"><form:input path="price" /></td>
								</tr>
								<tr>
									<td class="td1">地址：</td>
									<td class="td2" colspan="3"><form:input path="address"
											style="width:70%;" onchange="searchByStationName()" /></td>
								</tr>
								<tr>
									<td colspan="4">
										<div class="header">
											<h3>&nbsp;&nbsp;人员信息</h3>
										</div></td>
								</tr>
								<tr>
									<td class="td1">责任人：</td>
									<td class="td2"><input id="useStaffId" name="useStaffId"
										value="${model.useStaffId}" style="display:none" /> <isperp:listSelector
											autocomplete="true" id="cusUserIdSelector"
											afterSelectEmpty="clearCusUser();"
											afterSelected="setDepartmentNameFromUseStaff()"
											displayColumn="fullname" autocompleteUrl="customer/user/list"
											displayValue="${model.useStaffName}" valueColumn="id"
											valueControlId="useStaffId" name="useStaffName"
											displayValueCssClass="required" url="customer/user/list">
											<isperp:column name="id" title="id" hidden="true"></isperp:column>
											<isperp:column name="fullname" title="名称" width="150">
											</isperp:column>
											<isperp:column name="email" title="邮件" width="80">
											</isperp:column>
											<isperp:column name="tel" title="电话" width="150">
											</isperp:column>
											<isperp:column name="mobile" title="手机" width="80">
											</isperp:column>
											<isperp:column name="department_name" title="所属部门" width="80">
											</isperp:column>

										</isperp:listSelector>
									</td>
									<td class="td1">部门：</td>
									<td class="td2"><form:input path="departmentName" /><a
										href="javascript:void(0)"
										onclick="setDepartmentNameFromUseStaff()" class="nui-txt-link">根据责任人获取</a>
									</td>



								</tr>
								<tr>
									<td class="td1">管理者：</td>
									<td class="td2"><form:hidden path="managementStaffId" />
										<isperp:listSelector id="managementStaffIdSelector"
											url="customer/user/list?customerId=${model.cusCustomerId }"
											name="managementStaffName"
											displayValue="${model.managementStaffName }"
											valueControlId="managementStaffId">
											<isperp:column name="id" title="id" hidden="true"></isperp:column>
											<isperp:column name="name" title="名称" width="80">
											</isperp:column>
											<isperp:column name="type" title="类型" width="60">
											</isperp:column>
											<isperp:column name="sex" title="性别" width="60">
											</isperp:column>

											<isperp:column name="mobile" title="手机" width="100">
											</isperp:column>
											<isperp:column name="title" title="职务" width="100">
											</isperp:column>
										</isperp:listSelector></td>

									<td class="td1">维护者：</td>
									<td class="td2"><form:hidden path="supportStaffId" /> <isperp:listSelector
											id="supportStaffIdSelector"
											url="customer/user/list?customerId=${model.cusCustomerId }"
											name="supportStaffName"
											displayValue="${model.supportStaffName }"
											valueControlId="supportStaffId">
											<isperp:column name="id" title="id" hidden="true"></isperp:column>

											<isperp:column name="name" title="名称" width="80">
											</isperp:column>
											<isperp:column name="type" title="类型" width="60">
											</isperp:column>
											<isperp:column name="sex" title="性别" width="60">
											</isperp:column>

											<isperp:column name="mobile" title="手机" width="100">
											</isperp:column>
											<isperp:column name="title" title="职务" width="100">
											</isperp:column>
										</isperp:listSelector></td>

								</tr>
						</table>
					</div>
					<%-- 资产二维码
					
					<c:if test="${(editStatus eq 1) and (not empty model.code )}">
						<div style="position: absolute;top:0px;right:10px;">
							<div style="width:170px;height:170px;">
								<img alt=""
									src="configuration/ci/getTwoDimension?code=${model.code }">
							</div>
						</div>
					</c:if> --%>




					<table class=" form-table" id="basicInfoTable2">
						<tr>
							<td colspan="4">
								<div class="header">
									<h3>&nbsp;&nbsp;生命周期信息</h3>
								</div>
							</td>
						</tr>

						<tr>
							<td class="td1">状态：</td>
							<td class="td2" colspan="3"><form:select path="status"
									data-allow-empty="true" items="${ciStatus }" itemLabel="name"
									itemValue="name" cssClass="required"></form:select></td>
						</tr>

						<tr>
							<td class="td1">采购日期：</td>
							<td class="td2"><form:input path="buyDate" type="date" /></td>
							<td class="td1">安装日期：</td>
							<td class="td2"><form:input path="installationDate"
									type="date" />
							</td>

						</tr>
						<tr>
							<td class="td1">在用日期：</td>
							<td class="td2"><form:input path="availableDate" type="date" />
							</td>
							<td class="td1">报废日期：</td>
							<td class="td2"><form:input path="expiredDate" type="date" />
							</td>
						</tr>

						<tr>
							<td colspan="4">
								<div class="header">
									<h3>&nbsp;&nbsp;维保信息</h3>
								</div></td>
						</tr>
						<tr>
							<td class="td1">制造商：</td>
							<td class="td2"><form:hidden path="manufacturerProviderId" />
								<isperp:listSelector id="manufacturerProviderName"
									url="provider/provider/list"
									displayValue="${model.manufacturerProviderName }"
									name="manufacturerProviderName"
									valueControlId="manufacturerProviderId">
									<isperp:column name="id" title="id" hidden="true"></isperp:column>
									<isperp:column name="code" title="编号" width="80">
									</isperp:column>
									<isperp:column name="name" title="名称" width="150">
									</isperp:column>
									<isperp:column name="linkman" title="联系人" width="80">
									</isperp:column>
									<isperp:column name="linktel" title="联系电话" width="80">
									</isperp:column>
									<isperp:column name="serviceTel" title="客服电话" width="80">
									</isperp:column>
									<isperp:column name="supportTel" title="技术支持电话" width="80">
									</isperp:column>
								</isperp:listSelector></td>

							<td class="td1">供应商：</td>
							<td class="td2"><form:input path="provider" cssClass="" />
							</td>
						</tr>



						<tr>
							<td class="td1">维保商：</td>
							<td class="td2"><form:hidden path="maintainerProviderId" />
								<isperp:listSelector id="maintainerProviderIdSelector"
									url="provider/provider/list" name="maintainerProviderName"
									displayValue="${model.maintainerProviderName }"
									valueControlId="maintainerProviderId">
									<isperp:column name="id" title="id" hidden="true"></isperp:column>
									<isperp:column name="code" title="编号" width="80">
									</isperp:column>
									<isperp:column name="name" title="名称" width="150">
									</isperp:column>
									<isperp:column name="linkman" title="联系人" width="80">
									</isperp:column>
									<isperp:column name="linktel" title="联系电话" width="80">
									</isperp:column>
									<isperp:column name="serviceTel" title="客服电话" width="80">
									</isperp:column>
									<isperp:column name="supportTel" title="技术支持电话" width="80">
									</isperp:column>
								</isperp:listSelector>
							</td>

							<td class="td1">维保日期：</td>
							<td class="td2"><form:input path="maintainerStartDate"
									type="date" style="width:70px" /> 到 <form:input
									path="maintainerEndDate" type="date" style="width:70px" />
							</td>
						</tr>

						<tr>
							<td class="td1">保修电话：</td>
							<td class="td2" colspan="3"><form:input path="repairTel" />
							</td>

						</tr>
						<tr>
							<td class="td1">维保合同：</td>
							<td class="td2" colspan="3"><isperp:uploader
									sourceId="${model.id }" id="ciContracts"></isperp:uploader>
							</td>
						</tr>

						<tr>
							<td class="td1">备注：</td>
							<td class="td2" colspan="3"><form:textarea path="meno"
									style="width:70%;" /></td>
						</tr>
						</tbody>
					</table>
				</div>

				<div id="ciPropertyDetail" class="box  no-border">
					<div class="header">
						<h3>&nbsp;&nbsp;扩展信息（不同类别的资产有不同的属性）</h3>
					</div>
					<div id="ciPropertyTableLoading"></div>
					<table id="ciPropertyTable" class="form-table"
						style="table-layout: auto">
					</table>
				</div>
				<div class="box no-border">
					<div class="header">
						<h3>&nbsp;&nbsp;其它信息</h3>
					</div>
					<table class=" form-table">
						<tbody>
							<tr>
								<td class="td1">创建者：</td>
								<td class="td2">${model.creatorName }</td>
								<td class="td1">创建时间：</td>
								<td class="td2">${model.createDate }</td>
							</tr>

							<tr>
								<td class="td1">最后变更者：</td>
								<td class="td2">${model.modifierName }</td>
								<td class="td1">变更时间：</td>
								<td class="td2">${model.modifyDate }</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>

			<div id="relatedCi">
				<isperp:ciUseRelateCi relationId="${model.id }" id="rci" viewOnly="${readonly }"
					confCategoryId="${model.confCategoryId }"></isperp:ciUseRelateCi>
			</div>

			<div id="relatedDataLog">
				<div id="relatedDataLogInfo"></div>
				<script type="text/javascript">
					$.get("configuration/ci/ciDataChangedLog?id=${model.id}", function(data) {
						$("#relatedDataLogInfo").html(data);

						$('#ciDataLogCount').text($(data).find("#ciDataLogCount").val());
					});
				</script>
			</div>
			<div id="relatedIncident">
				<div id="relatedIncidentInfo"></div>
				<script type="text/javascript">
					$.get("configuration/ci/ciFailureResume?id=${model.id}", function(data) {
						$("#relatedIncidentInfo").html(data);
						$('#ciIncidentCount').text($(data).find("#ciIncidentCount").val());
					});
				</script>
			</div>
			<div id="relatedChange">
				<div id="relatedChangeInfo"></div>
				<script type="text/javascript">
					$.get("configuration/ci/ciChangeResume?id=${model.id}", function(data) {

						$("#relatedChangeInfo").html(data);

						$('#ciChangeCount').text($(data).find("#ciChangeCount").val());
					});
				</script>
			</div>
			<div id="relatedTaskCiInspect">
				<div id="relatedTaskCiInspectInfo"></div>
				<script type="text/javascript">
					$.get("configuration/ci/ciInspectResume?id=${model.id}", function(data) {
					
						$("#relatedTaskCiInspectInfo").html(data);
						$('#ciInspectCount').text($(data).find("#ciInspectCount").val());
					});
				</script>
			</div>
			<c:if test="${(ty ne 'sparepartIn') or (empty ty) }">
				<div id="relatedSparepart">
					<isperp:grid url="sparepart/sparepartRelation/findCiSparepart"
						urlExtScript="function(){return '?ciId=${model.id }'}"
						gridId="ciRelationSparepartGrid" showPager="true" height="auto"
						showSearchbar="false" sortname="create_date" sortorder="desc"
						showToolbar="false" cusActions="gridActions(rowObject)"
						loadComplete="$('#ciRelatedCiSparepartCount').text( ciRelationSparepartGrid.jqGrid.getGridParam('records'));">
						<jsp:attribute name="toolbar">
						</jsp:attribute>
						<jsp:body>
							<isperp:column name="id" title="id" hidden="true"></isperp:column>
							<isperp:column name="code" title="编号">
							</isperp:column>
							<isperp:column name="memo" title="描述">
							</isperp:column>
							<isperp:column name="creator_name" title="填表人">
							</isperp:column>
							<isperp:column name="create_date" title="填报日期">
							</isperp:column>
							<isperp:column name="ktype" title="类型">
							</isperp:column>
							<isperp:column name="type_key" title="类型1" hidden="true">
							</isperp:column>
							<isperp:column name="status" title="流程状态">
							</isperp:column>
						</jsp:body>
					</isperp:grid>
				</div>
			</c:if>
		</div>

	</div>

</form:form>

<input type="hidden" id="ciSelectorIds">
<isperp:listSelector id="ciSelector" displayValueCssClass="hidden"
	selectorCssClass="hidden" showClearBtn="false"
	url="configuration/ciRelation/listRelation?fromId=${model.id}"
	afterSelected="ciSelector_afterSelected(rows);" multiselect="true">
	<isperp:column name="id" title="id" hidden="true"></isperp:column>
	<isperp:column name="code" title="编号" width="80">
	</isperp:column>

	<isperp:column name="name" title="名称" width="100">
	</isperp:column>
	<isperp:column name="secretLevel" title="密级" width="60">
	</isperp:column>
	<isperp:column name="status" title="状态" width="60">
	</isperp:column>
	<isperp:column name="confCategoryName" title="类别" width="80">
	</isperp:column>
	<isperp:column name="departmentName" title="部门" width="100">
	</isperp:column>
	<isperp:column name="useStaffName" title="使用人" width="60">
	</isperp:column>
	<isperp:column name="address" title="位置" width="60">
	</isperp:column>
	<isperp:column name="meno" title="备注" width="80">
	</isperp:column>
</isperp:listSelector>

<isperp:buttonList>

	<c:if test="${(editStatus ne 0) or (empty editStatus)}">
		<button class="submit nui-mainbtn"
			onclick="submitCiForm();return false;">
			<span class="icon icon-save"></span>保存
		</button>
	</c:if>
</isperp:buttonList>

<input type="hidden" id="relationTypeId">

<script type="text/javascript">
	function rebuildAllRelation() {

		isperp.confirmAlert("您确定要重新生成此资产项的关联关系吗？<br><span style='color:red'>警告：此功能将会现有的配置关联，请谨慎使用！</span>", {
			yes : function() {
				isperp.showLoading();

				$.post("configuration/ciRelation/rebuildAll?changeId=${changeId }id=" + $("#id").val(), function(data) {
					if (data.success) {
						ciRelationGrid.reload();
						isperp.alert("重建成功！");
					} else {
						isperp.errorAlert(data.data);
					}
					isperp.hideLoading();

				});
			}
		});

	}

	function relatedCi_beforeClick() {
		var eStatus = $("#editStatus").val();

		if (eStatus == "1") {
			isperp.alert("请先保存资产信息！");
			return false;
		}
		return true;

	}
</script>
<script type="text/javascript">
	var initPryMap = new Map();//存储页面初始化的资产属性包括基本属性与扩展属性
	$(document).ready(function() {
		setCategoryProperty();
		var tCiId = $("#id").val();
		$.ajax({
			url : "configuration/ciRelation/getCiRelateCount",
			data : {
				ciId : tCiId
			},
			success : function(data) {
				$("#ciRelatedCiCount").text(data);
			}
		});
	 
	});

	function edituseStaffUser() {

		var userId = $("#useStaffId").val();
		if (userId == undefined || userId == "") {
			isperp.alert("请先选择负责人");
			return false;
		}

		isperp.openDialog({
			contentUrl : "customer/user/edit?id=" + userId,
			windowSize : "normal"
		});

	}
	
	

	function ciRelationGridEditCi(id) {
		var row = ciRelationGrid.getRowData(id);
		isperp.openDialog({
			contentUrl : "configuration/ci/edit?id=" + row.to_id
		});

	}

	function selectRelation(relationTypeId) {
		var propertyList = getPropertyControlValues();

		isperp.submitForm({
			formId : "ciForm",
			data : {
				"propertyList" : propertyList
			},
			success : function() {

				var $cateId = $("#confCategoryId");
				$cateId.attr("disabled", "disabled");
				$("#relationTypeId").val(relationTypeId);
				ciSelectorSelector.setParam("relationTypeId=" + relationTypeId + "&customerId=" + $("#cusCustomerId").val());

				$('#ciSelector').click();
			}
		});
		return false;

	}

	function cusCustomerId_afterSelected(rows) {
		if (rows.length < 1) {
			isperp.alert("没有数据被选择！")
			return false;
		}
 
	}

	function useStaffSelector_afterSelected(rows) {
		if (rows.length < 1) {
			return false;
		}
		var departmentName = rows[0].department, address = rows[0].linkaddress, $departmentName = $("#departmentName"), $address = $("#address");

		if ($departmentName.val() == "") {
			$departmentName.val(departmentName);
		} else if ($departmentName.val() != departmentName) {
			isperp.confirmAlert("资产部门【" + $departmentName.val() + "】与责任人部门【" + departmentName + "】不一致，是否更新为责任人部门？", {
				yes : function() {
					$departmentName.val(departmentName);
				}
			});
		}
		 
	}

	function setDepartmentNameFromUseStaff() {
		var userId = $("#useStaffId").val();
		if (userId == "") {
			return;
		}
		$.get("customer/user/getUser?id=" + userId, function(data) {
			$("#departmentName").val(data.department_name);
		});
	}

	function setAddressFromUseStaff() {
		var userId = $("#useStaffId").val();
		if (userId == "") {
			isperp.alert("请选择责任人！");
			return;
		}
		$.get("customer/user/getUser?id=" + userId, function(data) {
			$("#address").val(data.linkaddress);
		});
	}

	function ciSelector_afterSelected(rows) {
		if (rows.length < 1) {
			isperp.alert("没有数据被选择！");
			return;
		}
		var ids = rows[0].id;
		for ( var i = 1; i < rows.length; i++) {
			var item = rows[i];
			ids = ids + "," + item.id;
		}

		$.post("configuration/ciRelation/batchSave", {
			relationTypeId : $("#relationTypeId").val(),
			fromId : '${model.id}',
			toIds : ids
		}, function(data) {
			location.reload()
		});

	}

	//提交配置项表达
	function submitCiForm() {
		//edit at 20150427
		var map = new Map(); //
		var afterEditPropetyMap = getPagePropetyMap(map);//所有的资产属性的id与值的map
		var compareResult = compareProperty(initPryMap, afterEditPropetyMap);//比较前后变化

		isperp.showLoading({
			onThisWindow : true
		});
		var propertyList = getPropertyControlValues();
		
		//如果是入库资产，则需要保存关系数据
		var ty='${ty}';
		var typeKey="";
		if(ty=='sparepartIn')
		{
		   typeKey=ty;
		   sparepartId='${sourceId}';
		   $.ajax({
			type : "POST",
			url : "sparepart/sparepartRelation/saveRelation",
			data : {
				ciId : $("#code").val(),
				sparepartId:sparepartId,
				typeKey:typeKey
			},
			async : false,
			dataType : "json",
			success : function(data) {
			if(data.success==false)
			  isperp.alert(data.data);
			}
		});
		}
		
		

		var s = isperp.submitForm({
			formId : "ciForm",
			data : {
				"propertyList" : propertyList,
				"changeConfigurationList" : compareResult
			},
			success : function() {
				//isperp.alert("资产配置保存成功！");
				isperp.excuteParentFucById("returnExcuteFunDivId");
				isperp.reloadParentControl();
				isperp.closeDialog();
			}
		});

		isperp.hideLoading({
			onThisWindow : true
		});

		return false;

	}

	function compareProperty(oldPropertyMap, newPropertyMap) {

		var jsonResult = "[";
		var ciId = $("#id").val();
		var changeId = '${changeId }';
		var lsize = oldPropertyMap.size();
		if (lsize > newPropertyMap.size()) {
			lsize = newPropertyMap.size();
		}

		for ( var i = 0; i < lsize; i++) {
			if (oldPropertyMap.element(i).value != newPropertyMap.element(i).value) {
				var columnkey = oldPropertyMap.element(i).key;
				var columnvalue = newPropertyMap.element(i).value;
				var columnvalueOld = oldPropertyMap.element(i).value;
				var isCategoryProprety = "0";
				if (oldPropertyMap.element(i).key.substring(0, 2) == "c_") {
					isCategoryProprety = "1";
					columnkey = oldPropertyMap.element(i).key.substring(2);
				}

				jsonResult += "{'changeId':'" + changeId + "','ciId':'" + ciId + "','columnkey':'" + columnkey + "','columnvalue':'" + columnvalue + "','columnvalueBefore':'" + columnvalueOld + "','isCategoryProprety':'" + isCategoryProprety + "'},";
			}
		}
		jsonResult = jsonResult.substring(0, jsonResult.length - 1);
		jsonResult += "]";
		return jsonResult;
	}

	//设置分类的自定义属性并设置ci中所关联的值或者默认值
	function setCategoryProperty(ids,names,treeNode) {
		var confCategoryIdVal = ids||$("#confCategoryId").val();
		if (confCategoryIdVal == undefined || confCategoryIdVal == "") {
			$("#ciPropertyTable").empty();
			return false;
		}
		
		$("#ciPropertyTableLoading").html("载入自定义属性中...");

		$.getJSON("configuration/category/property/listByCategory?categoryId=" + confCategoryIdVal, function(data) {

			$("#ciPropertyTableLoading").empty();
			var col = 2;
			var rStr = "";
			$(data).each(function(index, item) {
			    
			    if(item.name.indexOf("经度")>-1)
			    {
			      $("#tmp_lng").val("c_"+item.id);
			    }
			    if(item.name.indexOf("纬度")>-1)
			    {
			      $("#tmp_lat").val("c_"+item.id);
			    }
			
				col--;
				rStr += "<td class='td1'>" + item.name + "：</td><td class='td2'>" + createControl(item) + "</td>"
				if (index % 2 != 0) {
					var row = "<tr>" + rStr + "</tr>"
					rStr = "";
					col = 2;
					$("#ciPropertyTable").append(row);

				}
			});

			if (rStr != "") {
				$("#ciPropertyTable").append("<tr>" + rStr + "</tr>");
				rStr = "";
			}

			setCiPropertyValue();
			isperp.initElement("#ciPropertyTable");
			//存储资产所有属性，当保存时如果存在改变的属性，则提交到后台记录
			//edit at 20150427
			getPagePropetyMap(initPryMap);

		});

		setRelation(confCategoryIdVal);

	}

	function getPagePropetyMap(map) {

		$("[id^='basicInfoTable'] input").each(function() {
			var obj_input = $(this);
			var obj_id = $(this).attr("name");
			var obj_value = $(this).val();
			map.put(obj_id, obj_value);

		});
		$("[id^='basicInfoTable'] select").each(function() {
			var obj_input = $(this);
			var obj_id = $(this).attr("name");
			var obj_value = $(this).val();

			map.put(obj_id, obj_value);

		});
		$("[id^='basicInfoTable'] textarea").each(function() {
			var obj_input = $(this);
			var obj_id = $(this).attr("name");
			var obj_value = $(this).val();
			map.put(obj_id, obj_value);

		});

		$("#ciPropertyTable input").each(function() {
			var obj_input = $(this);
			var obj_id = $(this).attr("id");
			var obj_value = $(this).val();
			map.put(obj_id, obj_value);

		});
		$("#ciPropertyTable select").each(function() {
			var obj_input = $(this);
			var obj_id = $(this).attr("id");
			var obj_value = $(this).val();

			map.put(obj_id, obj_value);

		});

		return map;

	}

	function setRelation(val) {
		$.ajax({
			url : "configuration/ciRelationType/listRelationTypes?fromCategoryId=" + val,
			cache : false,
			success : function(data) {

				var html = "";
				$(data).each(function(index, item) {
					html += "<button  type='button' class='nui-mainbtn' onclick='selectRelation(\"" + item.id + "\")'><span class='icon icon-plus'></span>" + item.name + "</button>";
				});

				$("#addRelationBtns").html(html);

			}

		});
	}
	//设置自定义ci的属性
	function setCiPropertyValue() {

		$.ajax({
			type : "POST",
			url : "configuration/ci/listProperty",
			data : {
				id : $("#id").val()
			},
			async : false,
			dataType : "json",
			success : function(data) {
				$(data).each(function(index, item) {

					$("#c_" + item.confCategoryPropertyId).val(item.value);

				});
			}
		});
	}

	//获取自定义属性的值
	function getPropertyControlValues() {
		var $input = $("#ciPropertyTable input");
		var $select = $("#ciPropertyTable select");

		var count = 0;
		var result = "[";
		$($input).each(function(index, item) {
			var $el = $(item);

			if ($el.attr("id") && $el.val()) {

				if (count == 0) {
					result += "{'confCategoryPropertyId':'" + $el.data("id") + "','value':'" + $el.val() + "'}"
				} else {
					result += ",{'confCategoryPropertyId':'" + $el.data("id") + "','value':'" + $el.val() + "'}"
				}
				count++;
			}
		});
		$($select).each(function(index, item) {
			var $el = $(item);
			if ($el.attr("id") && $el.val()) {
				if (count == 0) {
					result += "{'confCategoryPropertyId':'" + $el.data("id") + "','value':'" + $el.val() + "'}"
				} else {
					result += ",{'confCategoryPropertyId':'" + $el.data("id") + "','value':'" + $el.val() + "'}"
				}
				count++;
			}
		});

		return result + "]";
	}

	//构建input元素
	function createInputElement(item, cssCls) {
		var controlStr = "<input type='" + item.data_type + "' id='c_" + item.id + "' data-id='" + item.id + "' class='" + cssCls;

		if (item.notnull) {
			controlStr += " required";
		}

		controlStr += "' />"
		return controlStr;
	}

	//构建自定义属性输入控件
	function createControl(item) {
		var controlStr = "";
		var cssCls = "";
		switch (item.data_type) {
		case "string":
			controlStr = createInputElement(item, cssCls);
			break;
		case "number":
			cssCls = "number";
			item.data_type = "text";
			controlStr = createInputElement(item, cssCls);
			break;
		case "date":
		case "datetime":
			controlStr = createInputElement(item, cssCls);
			break;
		case "textarea":
			controlStr = "<textarea  id='c_" + item.id + "' data-id='" + item.id + "' class='" + cssCls;

			if (item.notnull) {
				controlStr += " required";
			}

			controlStr += "'></textarea>";
			break;

		case "select":
			controlStr = "<select  id='c_" + item.id + "'   data-id='" + item.id + "' ";
			if (item.notnull) {
				controlStr += " class='required'>";
			} else {
				controlStr += " >";
			}

			controlStr += "<option value=''></option>";

			if (item.items) {

				var itemArr = item.items.split("|");

				$(itemArr).each(function(i, it) {
					controlStr += "<option value='"+it+"'>" + it + "</option>";
				});
			}

			controlStr += "</select>";
			break;

		}

		return controlStr;

	}
</script>
